package com.sicong.admin.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sicong.admin.dto.PermissionNode;
import com.sicong.admin.entity.Permission;
import com.sicong.admin.service.PermissionService;
import com.sicong.admin.util.TreeUtil;
import com.sicong.common.annotation.Log;
import com.sicong.common.core.utils.Result;
import com.sicong.common.core.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author chenww
 * @since 2020-11-25
 */
@Api(tags = {"权限控制器"})
@RestController
@RequestMapping("/permission")
public class PermissionController {

    @Resource
    private PermissionService permissionService;

    @ApiOperation("添加权限")
    @PostMapping("/save")
    public Result<Void> savePermission(Permission permission) {
        permissionService.savePermission(permission);
        return ResultUtil.success();
    }

    @ApiOperation("删除权限")
    @DeleteMapping("/{permissionIds}")
    public Result<Void> removePermissions(@ApiParam("权限id") @PathVariable String permissionIds) {
        permissionService.removeByIds(Arrays.asList(permissionIds.split(",")));
        return ResultUtil.success();
    }

    @ApiOperation("修改权限信息")
    @PatchMapping("/{id}")
    public Result<Void> updatePermission(Permission permission) {
        permissionService.updateById(permission);
        return ResultUtil.success();
    }

    @Log("查询权限信息")
    @ApiOperation("查询权限信息")
    @GetMapping("/")
    public Result<List<PermissionNode>> getPermissions(@ApiParam("根节点id") Long root) {
        List<Permission> permissions = permissionService.list(Wrappers.<Permission>lambdaQuery()
                .select(Permission::getId, Permission::getPid,Permission::getPermission,
                        Permission::getPermissionName, Permission::getPath,
                        Permission::getComponent, Permission::getIcon,
                        Permission::getSort, Permission::getKeepAlive,
                        Permission::getStatus, Permission::getType));
        return ResultUtil.success(TreeUtil.buildTree(permissions,root));
    }

}

